import React, { Component } from 'react';
import {
  Form,
  Select,
  Button,
  Card,
  DatePicker,
  message,
  Modal,
  Table
} from 'antd';
import ajax from '../../utils/ajax';
import locale from 'antd/lib/date-picker/locale/zh_CN';

const Option = Select.Option;
const FormItem = Form.Item;
const { RangePicker } = DatePicker;

export default class Order extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      orderInfo: {},
      list: [],
      selectedRowKeys: '',
      selectedItem: '',
      Pagination: {
        current: '1',
        pageSize: '10',
        pageSizeOptions: ['1', '5', '10', '30'],
        showQuickJumper: true,
        showSizeChanger: true
      }
    };
  }

  componentWillMount() {
    this.getList();
  }

  getList = () => {
    ajax.get('/order_info').then(res => {
      let list = res.result.list.map((item, index) => {
        item.key = index;
        return item;
      });
      let result = res.result;
      this.setState({
        list,
        Pagination: {
          current: result.page,
          pageSize: result.page_size,
          total: result.total_count,
          showTotal: () => {
            return `共${result.total_count}条`;
          },
          onChange: current => {
            this.getList(current);
          }
        }
      });
    });
  };
  openOrderDetail = () => {
    let item = this.state.selectedItem;
    if (!item) {
      Modal.info({
        title: '信息',
        content: '请先选择一条订单'
      });
      return;
    }
    window.open(`/#/common/order/detail/${item.id}`, '_blank');
  };

  closeOrder = () => {
    let { id, status } = this.state.selectedItem;
    if (status === 2) {
      Modal.info({
        title: '提示',
        content: '订单已结束',
        okText: '确认'
      });
    } else {
      ajax.get('/ebike_info', { params: { id } }).then(res => {
        this.setState({
          visible: true,
          orderInfo: res.result
        });
      });
    }
  };

  onRowClick = (record, index) => {
    let selectKey = [index];
    this.setState({
      selectedRowKeys: selectKey,
      selectedItem: record
    });
  };

  render() {
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 19 }
    };

    const columns = [
      {
        title: '订单编号',
        dataIndex: 'order_sn'
      },
      {
        title: '车辆编号',
        dataIndex: 'bike_sn'
      },
      {
        title: '用户名',
        dataIndex: 'user_name'
      },
      {
        title: '手机号',
        dataIndex: 'mobile'
      },
      {
        title: '里程',
        dataIndex: 'distance',
        render(distance) {
          return distance / 1000 + 'Km';
        }
      },
      {
        title: '行驶时长',
        dataIndex: 'total_time'
      },
      {
        title: '状态',
        dataIndex: 'status',
        render(v) {
          return v === 1 ? '进行中' : '已完成';
        }
      },
      {
        title: '开始时间',
        dataIndex: 'start_time'
      },
      {
        title: '结束时间',
        dataIndex: 'end_time'
      },
      {
        title: '订单金额',
        dataIndex: 'total_fee'
      },
      {
        title: '实付金额',
        dataIndex: 'user_pay'
      }
    ];

    return (
      <div>
        <Card>
          <FilterForm />
        </Card>
        <Card style={{ marginTop: 10 }}>
          <Button type="primary" onClick={this.openOrderDetail}>
            订单详情
          </Button>
          <Button
            type="primary"
            style={{ marginLeft: 20 }}
            onClick={this.closeOrder}
          >
            结束订单
          </Button>
          <div style={{ marginTop: 20 }}>
            <Table
              bordered
              dataSource={this.state.list}
              columns={columns}
              pagination={this.state.Pagination}
              rowSelection={{
                type: 'radio',
                selectedRowKeys: this.state.selectedRowKeys
              }}
              onRow={(record, index) => {
                return {
                  onChange: () => {
                    this.onRowClick(record, index);
                  },
                  onClick: () => {
                    this.onRowClick(record, index);
                  }
                };
              }}
            />
          </div>
        </Card>

        <Modal
          title="结束订单"
          visible={this.state.visible}
          onCancel={() => {
            this.setState({
              visible: false
            });
          }}
          onOk={() => {
            this.setState({
              visible: false
            });
          }}
          width={600}
        >
          <Form layout="horizontal">
            <FormItem label="车辆编号" {...formItemLayout}>
              {this.state.orderInfo.bike_sn}
            </FormItem>
            <FormItem label="剩余电量" {...formItemLayout}>
              {this.state.orderInfo.battery + '%'}
            </FormItem>
            <FormItem label="行程开始时间" {...formItemLayout}>
              {this.state.orderInfo.start_time}
            </FormItem>
            <FormItem label="当前位置" {...formItemLayout}>
              {this.state.orderInfo.location}
            </FormItem>
          </Form>
        </Modal>
      </div>
    );
  }
}

// UI组件使用的纯函数
class FilterForm extends Component {
  handleSearch = () => {
    let searchInfo = this.props.form.getFieldsValue();
    message.success(JSON.stringify(searchInfo));
  };

  reSet = () => {
    this.props.form.resetFields();
  };

  render() {
    const { getFieldDecorator } = this.props.form;

    return (
      <Form layout="inline">
        <FormItem label="城市">
          {getFieldDecorator('city_id')(
            <Select style={{ width: 100 }} placeholder="全部">
              <Option value="">全部</Option>
              <Option value="1">北京市</Option>
              <Option value="2">天津市</Option>
              <Option value="3">深圳市</Option>
            </Select>
          )}
        </FormItem>
        <FormItem>
          {getFieldDecorator('date')(
            <RangePicker locale={locale} format="YYYY-MM-DD" />
          )}
        </FormItem>
        <FormItem label="订单状态">
          {getFieldDecorator('status')(
            <Select style={{ width: 100 }} placeholder="全部">
              <Option value="">全部</Option>
              <Option value="1">进行中</Option>
              <Option value="2">进行中(临时锁车))</Option>
              <Option value="2">行程结束</Option>
            </Select>
          )}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            style={{ margin: '0 20px' }}
            onClick={this.handleSearch}
          >
            查询
          </Button>
          <Button onClick={this.reSet}>重置</Button>
        </FormItem>
      </Form>
    );
  }
}
FilterForm = Form.create({})(FilterForm);
